package cn.demo.pm.service.impl;

import java.util.List;

import cn.demo.common.constant.CommonConstants;
import cn.demo.common.exception.ServiceException;
import cn.demo.common.utils.LockUtils;
import cn.demo.common.utils.SecurityUtils;
import cn.demo.pm.domain.PmIntegralBill;
import cn.demo.pm.domain.PmStoreGoods;
import cn.demo.pm.mapper.PmIntegralBillMapper;
import cn.demo.pm.mapper.PmStoreGoodsMapper;
import cn.demo.um.domain.UmClientUser;
import cn.demo.um.mapper.UmClientUserMapper;
import com.mybatisflex.core.paginate.Page;
import cn.demo.common.core.page.PageQuery;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.demo.pm.mapper.PmStoreOrderMapper;
import cn.demo.pm.domain.PmStoreOrder;
import cn.demo.pm.service.IPmStoreOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 积分商城订单Service业务层处理
 *
 * @author xtjun
 * @date 2024-06-06
 */
@Service
public class PmStoreOrderServiceImpl extends ServiceImpl<PmStoreOrderMapper, PmStoreOrder> implements IPmStoreOrderService {
    @Resource
    private PmStoreOrderMapper pmStoreOrderMapper;
    @Resource
    private PmStoreGoodsMapper storeGoodsMapper;
    @Resource
    private UmClientUserMapper clientUserMapper;
    @Resource
    private PmIntegralBillMapper integralBillMapper;
    /**
     * 查询积分商城订单
     *
     * @param id 积分商城订单主键
     * @return 积分商城订单
     */
    @Override
    public PmStoreOrder selectPmStoreOrderById(String id) {
        return pmStoreOrderMapper.selectOneById(id);
    }

    /**
     * 查询积分商城订单列表
     *
     * @param pmStoreOrder 积分商城订单
     * @return 积分商城订单
     */
    @Override
    public Page<PmStoreOrder> selectPmStoreOrderPage(PmStoreOrder pmStoreOrder, PageQuery pageQuery) {
        return pmStoreOrderMapper.paginate(pageQuery.build(), QueryWrapper.create(pmStoreOrder,PmStoreOrder.operators));
    }
    @Override
    public List<PmStoreOrder> selectPmStoreOrderList(PmStoreOrder pmStoreOrder) {
        return pmStoreOrderMapper.selectListByQuery(QueryWrapper.create(pmStoreOrder,PmStoreOrder.operators));
    }

    /**
     * 新增积分商城订单
     *
     * @param pmStoreOrder 积分商城订单
     * @return 结果
     */
    @Override
    public int insertPmStoreOrder(PmStoreOrder pmStoreOrder) {
        return pmStoreOrderMapper.insert(pmStoreOrder);
    }

    /**
     * 修改积分商城订单
     *
     * @param pmStoreOrder 积分商城订单
     * @return 结果
     */
    @Override
    public int updatePmStoreOrder(PmStoreOrder pmStoreOrder) {
        return pmStoreOrderMapper.update(pmStoreOrder);
    }

    /**
     * 批量删除积分商城订单
     *
     * @param ids 需要删除的积分商城订单主键
     * @return 结果
     */
    @Override
    public int deletePmStoreOrderByIds(List<String> ids) {
        return pmStoreOrderMapper.deleteBatchByIds(ids);
    }

    /**
     * 删除积分商城订单信息
     *
     * @param id 积分商城订单主键
     * @return 结果
     */
    @Override
    public int deletePmStoreOrderById(String id) {
        return pmStoreOrderMapper.deleteById(id);
    }

    @Override
    @Transactional
    public int addOrder(PmStoreOrder entry) {
        return LockUtils.lockFun("addOrder",entry.getGoodsId(),()->{

            String userId = SecurityUtils.getUserId();
            String deptId = SecurityUtils.getDeptId();
            PmStoreGoods goods = storeGoodsMapper.selectOneById(entry.getGoodsId());
            UmClientUser user = clientUserMapper.selectOneById(userId);
            long integral = goods.getIntegral() * entry.getGoodsNum();

            checkGoods(entry, goods);
            checkIntegral(entry,goods, user);

            // 创建订单
            entry.setUserId(userId);
            entry.setGoodsName(goods.getGoodsName());
            entry.setGoodsPic(goods.getGoodsPic());
            entry.setIntegral(integral);
            entry.setIsPay(1);
            entry.setOrderStatus(0);
            entry.setDeptId(deptId);
            int insert = pmStoreOrderMapper.insert(entry);

            // 生成账单
            PmIntegralBill bill = new PmIntegralBill();
            bill.setUserId(userId);
            bill.setIntegral(integral);
            bill.setDeptId(deptId);
            bill.setBillName("兑换商品【"+goods.getGoodsName()+"】");
            bill.setLinkId(entry.getId());
            bill.setBillType(2);
            integralBillMapper.insert(bill);

            // 扣减库存
            PmStoreGoods goodsParam = new PmStoreGoods();
            goodsParam.setId(goods.getId());
            goodsParam.setQuantity(goods.getQuantity() - entry.getGoodsNum());
            storeGoodsMapper.update(goodsParam);

            // 扣减积分
            UmClientUser userParam = new UmClientUser();
            userParam.setId(userId);
            userParam.setIntegral((null == user.getIntegral() ? 0 : user.getIntegral()) - integral);
            userParam.setIntegralUsed((null == user.getIntegralUsed() ? 0 : user.getIntegralUsed()) + integral);
            clientUserMapper.update(userParam);
            return insert;
        });
    }

    private void checkIntegral(PmStoreOrder entry, PmStoreGoods goods, UmClientUser user) {
        if (null == user.getIntegral() || goods.getIntegral() * entry.getGoodsNum() > user.getIntegral()){
            throw new ServiceException("积分不足，无法兑换");
        }
    }

    private static void checkGoods(PmStoreOrder entry, PmStoreGoods goods) {
        if (null == goods){
            throw new ServiceException("商品信息不存在");
        }
        if (CommonConstants.NO.equals(goods.getIsEnable())){
            throw new ServiceException("商品未上架");
        }
        if (entry.getGoodsNum() > goods.getQuantity()){
            throw new ServiceException("商品库存不足");
        }

    }
}
